package com.template.flows;

import co.paralleluniverse.fibers.Suspendable;
import com.template.states.IouState;
import net.corda.core.contracts.ContractState;
import net.corda.core.crypto.SecureHash;
import net.corda.core.flows.*;
import net.corda.core.transactions.SignedTransaction;
import org.jetbrains.annotations.NotNull;

import static net.corda.core.contracts.ContractsDSL.requireThat;

/**
 * IOU Create Responder flow
 *
 * @author yangjie
 * @date 2020/12/04
 */
@InitiatedBy(IouCreateFlow.class)
public class IouCreateResponderFlow extends FlowLogic<Void> {

    private FlowSession counterpartySession;

    public IouCreateResponderFlow(FlowSession counterpartySession) {
        this.counterpartySession = counterpartySession;
    }

    @Suspendable
    @Override
    public Void call() throws FlowException {
        SignedTransaction signedTransaction = subFlow(new SignTransactionFlow(counterpartySession) {
            @Override
            protected void checkTransaction(@NotNull SignedTransaction stx) throws FlowException {
                requireThat(require -> {
                    ContractState output = stx.getTx().getOutputs().get(0).getData();
                    require.using("This must be an IOU transaction.", output instanceof IouState);
                    IouState iou = (IouState) output;
                    require.using("The IOU's value can't be too high.", iou.getValue() < 100);
                    return null;
                });
            }
        });

        SecureHash expectedTxId = signedTransaction.getId();
        subFlow(new ReceiveFinalityFlow(counterpartySession, expectedTxId));

//        subFlow(new ReceiveFinalityFlow(counterpartySession));

        return null;
    }
}
